package com.weibo.gaollg;

import java.util.List;
import java.util.Map;

import net.vsame.url2sql.domain.Model;
import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.domain.Url2SqlModel;
import net.vsame.url2sql.domain.Url2SqlModelChain;
import net.vsame.url2sql.domain.UrlConfig;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.utils.JarUtils;
import net.vsame.url2sql.utils.JdbcUtils;

public class EditWebModel extends Url2SqlModel{

	@Override
	public void init() {
		System.out.println("url2sql-edit init...");
		try{
			WebHelper.init(null, null);
			initDatabase();
			initTable();
		}finally{
			WebHelper.remove();
		}
		
		/*
		UrlConfig urlConfig = new UrlConfig();
		urlConfig.setV("");
		urlConfig.setUrl("/h");
		urlConfig.setJs("var m = SQL.query('select * from student');this.put('m', m);");
		this.addGlobleUrlConfig(urlConfig);
		*/
		this.addUrlConfig("root", EditAction.class);
	}

	@Override
	public boolean isWeb() {
		return false;
	}
	
	public void initDatabase(){
		List<String> list = JdbcUtils.getAllTables();
		if(!list.contains("__url2sqlmapping")){
			//执行创建表语名
			String[] sqls = JarUtils.readResourceFromJar(EditWebModel.class, "init.sql").split(";");
			for(String sql : sqls){
				System.out.println(sql);
				JdbcUtils.execute(sql);
			}
		};
	}
	
	private static String getString(Object o){
		return o==null ? null : o+"";
	}
	
	public void initTable(){
		List<Model> list = JdbcUtils.queryList("SELECT * from __url2sqlmapping ORDER BY path");
		for(Map<String, Object> map : list){
			UrlConfig urlConfig = new UrlConfig();
			urlConfig.setUrl(getString(map.get("path")));
			urlConfig.setJs(getString(map.get("js")));
			urlConfig.setV(getString(map.get("v")));
			int status = (Integer) map.get("status");
			urlConfig.setStatus(status);
			
			if(urlConfig.getUrl().startsWith("/")){
				this.addGlobleUrlConfig(urlConfig);
			}else{
				this.addUrlConfig(urlConfig);
			}
		}
	}

	@Override
	public void invoke(Url2SqlModelChain chain) {
		Url2SqlContext context = WebHelper.getContext();
		System.out.println(context.getRequestUrl());
		if("/root/updatePath".equalsIgnoreCase(context.getRequestUrl())){
			context.putError(1, "unLogin");
			
		}
		super.invoke(chain);
	}
	
	

}
